package com.betterjr.modules.risk.loanmanage.dubbo;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

import javax.inject.Inject;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.betterjr.common.data.WorkUserInfo;
import com.betterjr.common.selectkey.SerialGenerator;
import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.BetterDateUtils;
import com.betterjr.common.utils.UserUtils;
import com.betterjr.common.web.AjaxObject;
import com.betterjr.modules.customer.ICustMechBankAccountService;
import com.betterjr.modules.customer.entity.CustMechBankAccount;
import com.betterjr.modules.risk.loan.dao.LoanProjectSynchInterfaces;
import com.betterjr.modules.risk.loan.entity.LoanProjectBank;
import com.betterjr.modules.risk.loan.entity.LoanProjectRelation;
import com.betterjr.modules.risk.loan.entity.LoanTransactionRelation;
import com.betterjr.modules.risk.loan.field.ConfigFieldCollections;
import com.betterjr.modules.risk.loan.service.LoanProjectRelationService;
import com.betterjr.modules.risk.loan.service.LoanTransactionRelationService;
import com.betterjr.modules.risk.loan.util.FutureUtil;
import com.betterjr.modules.risk.loan.util.HttpRequestBuilder;
import com.betterjr.modules.risk.loan.util.HttpRequestObject;
import com.betterjr.modules.risk.loanmanage.ILoanManageService;
import com.betterjr.modules.risk.loanmanage.entity.LoanData;
import com.betterjr.modules.risk.loanmanage.entity.PaymentPlan;
import com.betterjr.modules.risk.loanmanage.entity.RepaymentDetails;
import com.betterjr.modules.risk.loanmanage.remote.XmlUtil;
import com.betterjr.modules.risk.loanmanage.service.LoanDataService;
import com.betterjr.modules.risk.loanmanage.service.PaymentDataService;
import com.betterjr.modules.risk.loanmanage.service.PaymentPlanService;
import com.betterjr.modules.risk.loanmanage.service.RepaymentDetailsService;

/** 
 * @ClassName: FlowFacetsService 
 * @Description: 对外提供的流程服务
 * @author licz
 * @date 2017年11月6日 下午3:17:49 
 *  
 */
@Component
@Service(interfaceClass = ILoanManageService.class)
public class LoanManageDubboService implements ILoanManageService, LoanProjectSynchInterfaces {
    private static Logger logger = LoggerFactory.getLogger(LoanManageDubboService.class);
    public static final String CONSTANT_INTEREST = "0";// 利息
    public static final String CONSTANT_PRINCIPAL = "1";// 本金
    public static final String CONSTANT_SERVICE_FEE = "2";// 服务费
    public static final String CONSTANT_PAYMENT_GOODS = "4";// 账户监管规则 第3个选项 货款监控

    @Reference(interfaceClass = ICustMechBankAccountService.class)
    private ICustMechBankAccountService custMechBankAccountService;

    // 引用贷款合同服务 ，查询贷款合同详情
    @Inject
    private LoanProjectRelationService loanProjectRelationService;

    @Inject
    private LoanTransactionRelationService loanTransactionRelationService;

    // 引用 还款明细表服务，创建还款明细
    @Inject
    private RepaymentDetailsService repaymentDetailsService;

    // 引用 扣款计划服务，创建扣款记录
    @Inject
    private PaymentPlanService paymentPlanService;

    @Inject
    private PaymentDataService paymentDataService;

    @Inject
    private LoanDataService loanDataService;

    @Value("${web.prefix.fund.system.url}")
    private String prefixFundSystemUrl;

    /** 
     * <p>Description: </p> 
     * @see com.betterjr.modules.risk.loanmanage.ILoanManageService#saveLoanData(java.util.Map) 
     * @author licz
     * @date 2018年6月26日 下午2:26:37 
     */
    @Override
    public String saveLoanData(final Map<String, Object> anMap) {
        final WorkUserInfo operator = UserUtils.getUser();
        BTAssert.notNull(operator, "不能获取当前登陆用户！");
        final String contractId = anMap.get("contractId").toString();
        BTAssert.isTrue(StringUtils.isNotBlank(contractId), "contractId不能为空");

        // 校验是否存在 根据合同id
        if (CollectionUtils.isNotEmpty(loanDataService.selectByProperty("contractId", Long.parseLong(contractId)))) {
            BTAssert.isTrue(false, "贷款合同[" + contractId + "]已经录入放款数据，不能重复录入！");
        }

        setLoanContractInfo(anMap); // 赋值贷款合同信息

        final LoanData loanData = loanDataService.saveLoanData(anMap);// 创建放款数据记录
        final Long id = loanData.getId();

        createRepaymentDetails(anMap, id);// 创建还款明细
        // 回写贷款项目数据
        try {
            loanProjectRelationService.saveLoanRecord(loanData.getContractId());
        }
        catch (final Exception e) {
            BTAssert.isTrue(false, "回写贷款项异常saveLoanRecord！" + e.getMessage());
        }
        // 刷新数据中心的 交易数据状态: 由未放款变成已放款
        callDataCenterChangeLoanStatus(loanData, "1"); // 1表示未结清，2表示已结清
        return AjaxObject.newOk("成功").toJson();
    }

    public void callDataCenterChangeLoanStatus(final Long loanId, final String status) {
        callDataCenterChangeLoanStatus(loanDataService.selectByPrimaryKey(loanId), status);
    }

    /** 
     * @Title: callDataCenterChangeLoanStatus 
     * @Description: 
     * @param loanData    //status    1表示未结清，2表示已结清
     * @throws 
     * @author licz
     * @date 2018年7月16日 上午10:23:25 
     */
    public void callDataCenterChangeLoanStatus(final LoanData loanData, final String status) {

        final List<LoanTransactionRelation> loanTransactionRelations = loanTransactionRelationService
                .queryLoanTransactionRelations(loanData.getContractId());

        if (CollectionUtils.isNotEmpty(loanTransactionRelations)) {
            // String[] ids=new String[loanTransactionRelations.size()];
            final StringJoiner ids = new StringJoiner(",");
            loanTransactionRelations.forEach(action -> {
                ids.add(action.getTransactionNo());
            });
            final Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("status", status);
            paramMap.put("tradeIds", ids.toString().split(","));
            final HttpRequestObject httpRequestObject = HttpRequestBuilder.newInstance()
                    .url(prefixFundSystemUrl + ConfigFieldCollections.UPDATE_RANSACTION_DATA_STATUS_API_PATH)
                    .paramObject(JSONObject.toJSONString(paramMap))
                    .requestType(ConfigFieldCollections.REQUEST_HTTP_METHOD_POST).builder();
            /*final HttpRequestObject httpRequestObject = new HttpRequestObject();
            httpRequestObject.setUrl(ConfigFieldCollections.UPDATE_RANSACTION_DATA_STATUS_API_PATH);
            httpRequestObject.setParamObject(JSONObject.toJSONString(ids.toString().split(",")));
            httpRequestObject.setRequestType(ConfigFieldCollections.REQUEST_HTTP_METHOD_POST);*/
            FutureUtil.getHttpFuture(httpRequestObject);
            FutureUtil.removeFuture(httpRequestObject);

        }
    }

    private void createRepaymentDetails(final Map<String, Object> anMap, final Long loanDataId) {
        final String repaymentInterest = anMap.get("repaymentInterest").toString();
        final String repaymentInterestDate = anMap.get("repaymentInterestDate").toString();
        final String repaymentPrincipal = anMap.get("repaymentPrincipal").toString();
        final String repaymentPrincipalDate = anMap.get("repaymentPrincipalDate").toString();
        final String settlementFlag = anMap.get("settlementFlag").toString();

        final LoanProjectRelation loanContractInfo = (LoanProjectRelation) anMap.get("loanContractInfo");
        final RepaymentDetails repaymentDetails = new RepaymentDetails();
        repaymentDetails.setLoanDataId(loanDataId);
        repaymentDetails.setSettlementFlag(settlementFlag);// 息金提前结清标志 0表示是 1表示否
        repaymentDetails.setCreatorId(UserUtils.getUser().getId());
        repaymentDetails.setCreator(UserUtils.getUser().getName());
        repaymentDetails.setCreateDate(Timestamp.valueOf(BetterDateUtils.getDateTime()));
        repaymentDetails.setUpdateCreatorId(UserUtils.getUser().getId());
        repaymentDetails.setUpdateCreator(UserUtils.getUser().getName());
        repaymentDetails.setUpdateDate(Timestamp.valueOf(BetterDateUtils.getDateTime()));

        // 创建还息明细
        // repaymentDetails.setRepaymentMode(repaymentMode); // 扣款方式 废弃 目前无用，（现金，税票）
        repaymentDetails.setAmount(new BigDecimal(repaymentInterest));// 还息金额
        repaymentDetails.setRepaymentdate(new Timestamp(BetterDateUtils.parseDate(repaymentInterestDate).getTime()));// 还款日期
        repaymentDetails.setRepaymentType(CONSTANT_INTEREST); // 0 利息 ；1 本金
        repaymentDetails.setId(SerialGenerator.getLongValue(RepaymentDetails.selectKey));
        repaymentDetailsService.insertSelective(repaymentDetails);

        // 创建计划
        LoanProjectBank bankInfo = null;
        // 供应商可归集信息
        final StringJoiner accoJoiner = new StringJoiner(",");
        loanContractInfo.getCustAggregationBank().forEach(action -> accoJoiner.add(action.getBankAccoName()));
        // 账户监管规则
        final String ruleJsonInfo = getRuleJsonInfo(loanContractInfo);

        // 创建还息 扣款计划
        if (!"0".equals(settlementFlag)) {
            final PaymentPlan paymentInterestPlan = new PaymentPlan();
            paymentInterestPlan.setActivationFlag("0");// 默认都是计划都是激活的 需要推送过去 可以不设置
            paymentInterestPlan.setLoanDataId(loanDataId);
            paymentInterestPlan.setDetailsId(repaymentDetails.getId());
            paymentInterestPlan.setAmount(repaymentDetails.getAmount());
            paymentInterestPlan.setPaymentType(repaymentDetails.getRepaymentType());

            // 付款信息
            // paymentInterestPlan.setPaymentMode(repaymentDetails.getRepaymentMode());// 扣款方式 废弃 目前无用，（现金，税票）
            paymentInterestPlan.setPaymentDate(repaymentDetails.getRepaymentdate());
            paymentInterestPlan.setPaymentCustomerId(loanContractInfo.getCustNo());// 客户 id
            bankInfo = loanContractInfo.getCustWithHoldInterestBank();
            BTAssert.notNull(bankInfo, "供应商扣款利息账户为空！getCustWithHoldInterestBank()");
            logger.info("创建还息计划 -供应商扣款利息账户 -loanContractInfo.getCustWithHoldInterestBank():" + bankInfo.toString());
            paymentInterestPlan.setPaymentAccountName(bankInfo.getBankAccoName());// 账户
            paymentInterestPlan.setPaymentAccountNo(bankInfo.getBankAcco());// 账号
            paymentInterestPlan.setPaymentAccountBank(bankInfo.getBankName());// 开户行
            paymentInterestPlan.setPaymentBankNo(bankInfo.getBankNo());// 联行号
            paymentInterestPlan.setPaymentAccounts(accoJoiner.toString());// 可归集账户

            // 收款信息
            bankInfo = loanContractInfo.getFactoryGatheringInterestBank();
            BTAssert.notNull(bankInfo, "资金方收款利息账户为空！getFactoryGatheringInterestBank()");
            logger.info("创建还息计划 -资金方收款利息账户 -loanContractInfo.getFactoryGatheringInterestBank():" + bankInfo.toString());
            paymentInterestPlan.setReceiveAccountName(bankInfo.getBankAccoName());
            paymentInterestPlan.setReceiveAccountNo(bankInfo.getBankAcco());
            paymentInterestPlan.setReceiveAccountBank(bankInfo.getBankName());
            paymentInterestPlan.setReceiveBankNo(bankInfo.getBankNo());

            // 监控规则JSON字符
            paymentInterestPlan.setRuleJson(ruleJsonInfo);

            paymentPlanService.savePaymentPlan(paymentInterestPlan);// 创建扣款计划
        }

        // 还本 详情
        // repaymentDetails.setRepaymentMode(repaymentMode); // 扣款方式 废弃 目前无用，（现金，税票）
        repaymentDetails.setAmount(new BigDecimal(repaymentPrincipal));// 还息金额
        repaymentDetails.setRepaymentdate(new Timestamp(BetterDateUtils.parseDate(repaymentPrincipalDate).getTime()));// 还款日期
        repaymentDetails.setRepaymentType(CONSTANT_PRINCIPAL); // 0 利息 ；1 本金
        repaymentDetails.setId(SerialGenerator.getLongValue(RepaymentDetails.selectKey));
        repaymentDetailsService.insertSelective(repaymentDetails);

        // 创建 还本 扣款计划
        final PaymentPlan paymentPrincipalPlan = new PaymentPlan();
        paymentPrincipalPlan.setLoanDataId(loanDataId);
        paymentPrincipalPlan.setActivationFlag("0");// 默认都是计划都是激活的 需要推送过去 可以不设置
        paymentPrincipalPlan.setDetailsId(repaymentDetails.getId());
        paymentPrincipalPlan.setAmount(repaymentDetails.getAmount());
        paymentPrincipalPlan.setPaymentType(repaymentDetails.getRepaymentType());
        // paymentPrincipalPlan.setPaymentMode(repaymentDetails.getRepaymentMode());// 废弃 目前无用，（现金，税票）
        paymentPrincipalPlan.setPaymentDate(repaymentDetails.getRepaymentdate());
        paymentPrincipalPlan.setPaymentCustomerId(loanContractInfo.getCustNo());// 客户 id

        // 付款信息
        bankInfo = loanContractInfo.getCustWithHoldPrincipalBank();
        BTAssert.notNull(bankInfo, "供应商扣款本金账户为空！getCustWithHoldPrincipalBank()");
        logger.info("创建还本计划 -供应商扣款本金账户 -loanContractInfo.getCustWithHoldPrincipalBank():" + bankInfo.toString());
        paymentPrincipalPlan.setPaymentAccountName(bankInfo.getBankAccoName());// 账户
        paymentPrincipalPlan.setPaymentAccountNo(bankInfo.getBankAcco());// 账号
        paymentPrincipalPlan.setPaymentAccountBank(bankInfo.getBankName());// 开户行
        paymentPrincipalPlan.setPaymentBankNo(bankInfo.getBankNo());// 联行号
        paymentPrincipalPlan.setPaymentAccounts(accoJoiner.toString());// 可归集账户

        // 收款信息
        bankInfo = loanContractInfo.getFactoryGatheringPrincipalBank();
        BTAssert.notNull(bankInfo, "资金方收款本金账户为空！getFactoryGatheringPrincipalBank()");
        logger.info("创建还本计划 -资金方收款本金账户 -loanContractInfo.getFactoryGatheringPrincipalBank():" + bankInfo.toString());
        paymentPrincipalPlan.setReceiveAccountName(bankInfo.getBankAccoName());
        paymentPrincipalPlan.setReceiveAccountNo(bankInfo.getBankAcco());
        paymentPrincipalPlan.setReceiveAccountBank(bankInfo.getBankName());
        paymentPrincipalPlan.setReceiveBankNo(bankInfo.getBankNo());

        // 监控规则JSON字符
        paymentPrincipalPlan.setRuleJson(ruleJsonInfo);

        paymentPlanService.savePaymentPlan(paymentPrincipalPlan);// 创建扣款计划
    }

    /** 
     * @Title: getRuleJsonInfo 
     * @Description: 
     * @param loanContractInfo
     * @throws 
     * @author licz
     * @date 2018年6月29日 下午6:18:32 
     */
    private String getRuleJsonInfo(final LoanProjectRelation loanContractInfo) {
        final String holdRule = loanContractInfo.getWithHoldRule();
        final Map<String, Object> paymentHandMap = new HashMap<>();
        paymentHandMap.put("advanceDate", "3");// 提前监控监控日期
        paymentHandMap.put("tradeAmount",
                loanContractInfo.getBalance().setScale(2, BigDecimal.ROUND_HALF_UP).toString());// 融资项目对应的应付账款

        final StringJoiner withholdJoiner = new StringJoiner(",");
        // 包含规则2的； 就代表还款时监控账户 1 2 4 规则计算
        if (ArrayUtils.contains(new String[] { "2", "3", "6", "7" }, holdRule)) {
            withholdJoiner.add("2");
        }

        // 包含规则3的； 就代表还款时监控账户 1 2 4 规则计算
        if (ArrayUtils.contains(new String[] { "4", "5", "6", "7" }, holdRule)) {
            withholdJoiner.add("3");
        }
        paymentHandMap.put("withhold", withholdJoiner.toString());// 规则 例如 “2,3”
        return JSONObject.toJSONString(paymentHandMap);
    }

    /** 
     * @Title: setLoanContractInfo 
     * @Description: 查询贷款合同详情
     * @param anMap 
     * @throws 
     * @author licz
     * @date 2018年6月27日 下午2:20:08 
     */
    private void setLoanContractInfo(final Map<String, Object> anMap) {
        final String contractId = anMap.get("contractId").toString();
        final LoanProjectRelation obj = loanProjectRelationService
                .findLoanProjectReltionDetailById(Long.valueOf(contractId));
        BTAssert.notNull(obj, "LoanProjectRelation不能为空");
        logger.info("放款数据录入loanProjectRelationService.findLoanProjectReltionDetailById()：入参contractId[" + contractId
                + "];;;loanContractInfo:" + obj.toString());

        /*
        // test code start
        obj.setId(11111L);
        obj.setElcAggrementName("合同名称XXXX贷款");
        obj.setLoanAggrementNo("合同号111111");
        obj.setCustName("供应商企业A");
        obj.setCustCode("供应商企业代码52425");
        obj.setCustNo(123456L);
        obj.setCoreName("核心企业B");
        obj.setCoreNo(2525452L);
        obj.setFactoryName("资金提供公司C");
        obj.setFactoryNo(999999L);
        final LoanProjectBank x = new LoanProjectBank();
        x.setBankName("开户行 招商银行");
        x.setBankAcco("6225 0257 0258 886");
        x.setBankAccoName("李军");
        x.setBankNo("02154524545");
        obj.setCustWithHoldInterestBank(x);
        obj.setFactoryGatheringInterestBank(x);
        obj.setCustWithHoldPrincipalBank(x);
        obj.setCustWithHoldPrincipalBank(x);
        // test code end 
        */
        BTAssert.notNull(obj, "不能获取贷款合同信息！");
        anMap.put("contractId", obj.getId());
        anMap.put("contractName", obj.getElcAggrementName());
        anMap.put("contractNo", obj.getLoanAggrementNo());
        anMap.put("supplierName", obj.getCustName());
        anMap.put("supplierNo", obj.getCustCode());
        anMap.put("supplierId", obj.getCustNo());
        anMap.put("coreCompanyName", obj.getCoreName());
        anMap.put("coreCompanyId", obj.getCoreNo());
        anMap.put("fundProviderName", obj.getFactoryName());
        anMap.put("fundProviderId", obj.getFactoryNo());
        anMap.put("loanContractInfo", obj);
    }

    /** 
     * <p>Description: </p> 
     * @see com.betterjr.modules.risk.loanmanage.ILoanManageService#queryLoanData(java.util.Map, int, int, java.lang.String) 
     * @author licz
     * @date 2018年6月26日 下午2:26:37 
     */
    @Override
    public String listLoanDataByPage(final Map<String, Object> anMap, final int anPageNum, final int anPageSize,
            final String anFlag) {
        final WorkUserInfo operator = UserUtils.getUser();
        BTAssert.notNull(operator, "不能获取当前登陆用户！");
        return AjaxObject.newOkWithPage("成功", loanDataService.listLoanDataByPage(anMap, anPageNum, anPageSize))
                .toJson();
    }

    /** 
     * <p>Description: </p>   费用，无用了
     * @see com.betterjr.modules.risk.loanmanage.ILoanManageService#savaCutpaymentData(java.util.Map) 
     * @author licz
     * @date 2018年6月27日 上午10:21:02 
     */
    @Override
    public String transfer(final String corpCode, final String signData) {
        final String tradeCode = XmlUtil.getElNameText(signData, "tradeCode");// 操作XX业务
        // 调用 扣款数据 的录入
        if ("savePaymentData".equals(tradeCode)) {
            paymentPlanService.writeBackPlanData(signData);
        }
        return AjaxObject.newOk("成功").toJson();
    }

    /** 
     * <p>Description: </p> 
     * @see com.betterjr.modules.risk.loanmanage.ILoanManageService#savePaymentPlan(java.util.Map) 
     * @author licz
     * @date 2018年6月29日 上午10:20:21 
     */
    @Override
    public String savePaymentPlan(final Map<String, Object> anMap) {
        paymentPlanService.savePaymentPlan(anMap);
        return AjaxObject.newOk("成功").toJson();
    }

    /** 
     * <p>Description: </p> 
     * @see com.betterjr.modules.risk.loanmanage.ILoanManageService#cancelPaymentPlan(java.lang.Long) 
     * @author licz
     * @date 2018年6月29日 上午10:20:21 
     */
    @Override
    public String cancelPaymentPlan(final Long anPlanId) {
        paymentPlanService.cancelPaymentPlanById(anPlanId);
        return AjaxObject.newOk("成功").toJson();
    }

    /** 
     * <p>Description: </p> 
     * @see com.betterjr.modules.risk.loanmanage.ILoanManageService#manuallyCompletedRePayment(java.lang.Long) 
     * @author licz
     * @date 2018年6月29日 上午11:45:17 
     */
    @Override
    public String manuallyCompletedRePayment(final Long anId) {
        loanDataService.manuallyCompletedRePayment(anId);
        return AjaxObject.newOk("成功").toJson();
    }

    /** 
     * <p>Description: </p> 
     * @see com.betterjr.modules.risk.loanmanage.ILoanManageService#createAccountMonitoringPlan(java.lang.Long) 
     * @author licz
     * @date 2018年6月29日 下午2:23:51 
     */
    public String createAccountMonitoringPlan(final LoanProjectRelation loanContractInfo) {
        logger.info("创建服务费计划入参loanContractInfo：" + loanContractInfo.toString());

        // 创建 扣款计划
        final PaymentPlan paymentPrincipalPlan = new PaymentPlan();

        // 供应商可归集信息
        final StringJoiner accoJoiner = new StringJoiner(",");
        loanContractInfo.getCustAggregationBank().forEach(action -> accoJoiner.add(action.getBankAccoName()));

        // 账户监管是否勾选的规则----监控账户 1 2 4 规则计算
        final String holdRule = loanContractInfo.getWithHoldRule();
        String activationFlag = "1";// 1代表不监管
        // 第1个规则 创建监管计划----系统监控到资金方放款资金到账，立即划扣企e金服服务费
        if (ArrayUtils.contains(new String[] { "1", "3", "5", "7" }, holdRule)) {
            // 待表勾选了第1个 即扣取服务费
            activationFlag = "0";// 监管
            final Map<String, Object> paymentHandMap = new HashMap<>();
            paymentHandMap.put("advanceDate", "3");// 提前监控监控日期
            paymentHandMap.put("loanBalanceAmount",
                    loanContractInfo.getBalance().setScale(2, BigDecimal.ROUND_HALF_UP).toString());// 放款金额
            paymentHandMap.put("withhold", "1");// 规则
            paymentPrincipalPlan.setRuleJson(JSONObject.toJSONString(paymentHandMap));
        }

        paymentPrincipalPlan.setContractId(loanContractInfo.getId());
        paymentPrincipalPlan.setPaymentCustomerId(loanContractInfo.getCustNo());// 客户id
        // 平台服务费 服务费=贷款金额*费率/360*融资期限
        final BigDecimal amount = loanContractInfo.getLoanBalance().multiply(loanContractInfo.getServiceRate())
                .divide(new BigDecimal(360), 3, BigDecimal.ROUND_HALF_EVEN)
                .multiply(new BigDecimal(loanContractInfo.getFinancingMaturityDate()));
        paymentPrincipalPlan.setAmount(amount);
        paymentPrincipalPlan.setPaymentType(CONSTANT_SERVICE_FEE);// 服务费
        // paymentPrincipalPlan.setPaymentMode(repaymentDetails.getRepaymentMode());// 废弃 目前无用，（现金，税票）
        paymentPrincipalPlan
                .setPaymentDate(new Timestamp(BetterDateUtils.parseDate(loanContractInfo.getLoanDate()).getTime()));

        // 付款信息
        final LoanProjectBank bankInfo = loanContractInfo.getCustPayServiceBank();
        logger.info("创建服务费计划入参 -供应商付服务费账户 ：loanContractInfo-：loanContractInfo.getCustPayServiceBank()"
                + bankInfo.toString());
        paymentPrincipalPlan.setPaymentAccountName(bankInfo.getBankAccoName());// 账户
        paymentPrincipalPlan.setPaymentAccountNo(bankInfo.getBankAcco());// 账号
        paymentPrincipalPlan.setPaymentAccountBank(bankInfo.getBankName());// 开户行
        paymentPrincipalPlan.setPaymentBankNo(bankInfo.getBankNo());// 联行号
        paymentPrincipalPlan.setPaymentAccounts(accoJoiner.toString());// 可归集账户

        // 收款信息 获取企E平台的收款信息
        final List<CustMechBankAccount> banks = custMechBankAccountService.queryPlatformBankAccount();
        BTAssert.isTrue(!CollectionUtils.isEmpty(banks), "企E平台的收款银行信息不能为空!queryPlatformBankAccount()");
        final CustMechBankAccount bank = banks.get(0);
        logger.info("创建服务费计划 -企E平台的收款银行信息 -custMechBankAccountService.queryPlatformBankAccount()" + bank.toString());
        paymentPrincipalPlan.setReceiveAccountName(bank.getBankAccoName());
        paymentPrincipalPlan.setReceiveAccountNo(bank.getBankAcco());
        paymentPrincipalPlan.setReceiveAccountBank(bank.getBankName());
        paymentPrincipalPlan.setReceiveBankNo(bank.getPaySysNum());

        // 计划是否推送云资金
        paymentPrincipalPlan.setActivationFlag(activationFlag);

        // 调用创建PLAN
        paymentPlanService.savePaymentPlan(paymentPrincipalPlan);// 创建扣款计划

        return AjaxObject.newOk("成功").toJson();
    }

    /** 
     * <p>Description: </p> 
     * @see com.betterjr.modules.risk.loanmanage.ILoanManageService#cancelPaymentPlanByLoanId(java.lang.Long) 
     * @author licz
     * @date 2018年6月29日 下午2:23:51 
     */
    @Override
    public String cancelPaymentPlanByContractId(final Long contractId) {
        paymentPlanService.cancelPaymentPlanByContractId(contractId);
        return AjaxObject.newOk("成功").toJson();
    }

    /** 
     * <p>Description: </p > 
     * @see com.betterjr.modules.risk.loan.dao.LoanProjectSynchInterfaces#InvokeDeleted(com.betterjr.modules.risk.loan.entity.LoanProjectRelation) 
     * @author licz
     * @date 2018年7月3日 下午3:43:49 
     */
    @Override
    public void InvokeDeleted(final LoanProjectRelation anLoan) {

        try {
            cancelPaymentPlanByContractId(anLoan.getId());
        }
        catch (final Exception e) {
            BTAssert.notNull(null, "取消付款计划异常" + e.getMessage());
        }

    }

    /** 
     * <p>Description: </p > 
     * @see com.betterjr.modules.risk.loan.dao.LoanProjectSynchInterfaces#InvokeEffective(com.betterjr.modules.risk.loan.entity.LoanProjectRelation) 
     * @author licz
     * @date 2018年7月3日 下午3:43:49 
     */
    @Override
    public void InvokeEffective(final LoanProjectRelation anLoan) {

        loggerin.debug(" LoanManageDubboService  InvokeEffective " + anLoan);
        try {
            createAccountMonitoringPlan(anLoan);
        }
        catch (final Exception e) {
            BTAssert.notNull(null, "创建付款计划异常" + e.getMessage());
        }

    }

}
